<?php

namespace Largezhou\Admin\Form\Fields;

class MultipleSelect extends Select
{
    protected $component = 'admin-select';
    protected $default = [];

    public function __construct(string $fieldName, ...$args)
    {
        $this->props['multiple'] = true;
        $this->props['listStyle'] = 'v';

        return parent::__construct($fieldName, ...$args);
    }

    /**
     * 先用这种方式,禁止该组件设置multiple的值
     *
     * @param $multiple
     *
     * @return $this
     */
    public function multiple($multiple)
    {
        return $this;
    }

    /**
     * 下拉列表的样式,v - 垂直排列;h - 水平排列
     * 如果选项比较多,可以采用水平排列 - h
     *
     * @param $style
     *
     * @return MultipleSelect
     */
    public function listStyle($style)
    {
        return $this->props('listStyle', $style);
    }

    public function setValue($value)
    {
        $relatedKey = $this->getRelatedKeyName();

        $this->value = array_map(function ($v) use ($relatedKey) {
            return $v[$relatedKey];
        }, $value);

        return $this;
    }

    /**
     * 获取多对多关联中,关联关系另一边的主键名,一般为id
     *
     * @return string
     */
    protected function getRelatedKeyName()
    {
        $relation = call_user_func([$this->form->model(), $this->name()]);

        return $relation->getRelated()->getKeyName();
    }
}
